//
//  SetingViewController.m
//  Arts1
//
//  Created by lanou on 15/9/7.
//  Copyright (c) 2015年 Arts1. All rights reserved.
//

#import "SetingViewController.h"
#import "AllHeader.h"
#import "PersonalViewController.h"
#import "HomeListViewController.h"
#import "ServiceTermsViewController.h"
#import "ThanksViewController.h"
#import "ChatViewController.h"


@interface SetingViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic ,strong) UITableView *mainTableView;

@property (nonatomic ,strong) NSArray *dataSource;

@property (nonatomic ,strong) NSString *loginState;

@property (nonatomic ,assign) float siziCache;

@end

@implementation SetingViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = kBackgroundColor;
    self.navigationController.navigationBar.tintColor = kCustomColor(50, 50, 70, 1);
    
    self.navigationItem.title = @"设置";
    // Do any additional setup after loading the view.
    
    [self creactData];
    
    [self creactTableView];
    [self sizeCecha];
}

- (void)viewDidDisappear:(BOOL)animated{
    self.tabBarController.tabBar.hidden = NO;
    if (_hidrabBarBlock) {
        _hidrabBarBlock();
    }
}

- (void)creactData
{
    _dataSource = @[@[@"个人设置",@"清理缓存"],@"感激致谢",@[@"意见反馈",@"服务条款"],@"退出登录"];
}

//创建设置页面视图
- (void)creactTableView
{
    _mainTableView = [[UITableView alloc] initWithFrame:self.view.bounds style:(UITableViewStyleGrouped)];
    _mainTableView.backgroundColor = kBackgroundColor;
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    
    _mainTableView.bounces = YES;
    
    [self.view addSubview:_mainTableView];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0)
    {
        return 2;
    }
    else if (section == 1)
    {
        return 1;
    }
    else if (section == 2)
    {
        return 2;
    }else
    {
        return 1;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (cell == nil)
    {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cell"];
    }
    
    [cell setSelectionStyle:(UITableViewCellSelectionStyleGray)];
    
    switch (indexPath.section)
    {
        case 0:
            cell.textLabel.text = _dataSource[0][indexPath.row];
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            break;
        case 1:
            cell.textLabel.text = _dataSource[1];
            cell.textLabel.font = [UIFont systemFontOfSize:14];
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2fM",_siziCache];
            break;
        case 2:
        {
            cell.textLabel.text = _dataSource[2][indexPath.row];
            cell.textLabel.font = [UIFont systemFontOfSize:14];
        }
            break;
        case 3:
        {
            cell.textLabel.text = _dataSource[3];
            cell.textLabel.font = [UIFont systemFontOfSize:18];
            cell.textLabel.textAlignment = NSTextAlignmentCenter;
        }
            break;
            
        default:
            break;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    switch (indexPath.section)
    {
        case 0://第一个分区
        {
            if (indexPath.row == 0)//个人设置
            {
                NSLog(@"个人设置");
                // 进入个人设置页面
                PersonalViewController *personVC = [[PersonalViewController alloc] init];
                [self.navigationController pushViewController:personVC animated:YES];
            }
            else if (indexPath.row == 1)//清楚缓存
            {
                NSLog(@"清楚缓存");
                if([self folderSizeAtPath:[NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches/default"]] == 0)
                {
                    [self cachesIsNull];
                }
                else{
                    [self clearCaches];
                    
                }
                [self.mainTableView reloadData];
            }
        }
            break;
        case 1://第二个分区
        {

            NSLog(@"感激致谢");
            ThanksViewController *thanksVC = [[ThanksViewController alloc] init];
            [self.navigationController pushViewController:thanksVC animated:YES];

        }

            break;
        case 2://第三个分区
        {
            if (indexPath.row == 0)//系统设置
            {
                NSLog(@"系统设置");
                
//                RCConversationViewController *chatService = [[RCConversationViewController alloc] init];
                RCPublicServiceChatViewController *chatService = [[RCPublicServiceChatViewController alloc] init];
                chatService.conversationType = ConversationType_APPSERVICE;
                chatService.userName = @"客服";
                chatService.targetId = @"KEFU1445692157383";
//                chatService.conversationType = ConversationType_CUSTOMERSERVICE;
                
                // 把客服聊天视图控制器添加到导航栈。
                self.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:chatService animated:YES];
                self.hidesBottomBarWhenPushed = NO;
            }
            else if (indexPath.row == 1)//服务条款
            {
                NSLog(@"服务条款");
                //  服务条款
                ServiceTermsViewController *serviewVC = [[ServiceTermsViewController alloc] init];
                serviewVC.hidesBottomBarWhenPushed = YES;
                [self.navigationController pushViewController:serviewVC animated:YES];
                serviewVC.hidesBottomBarWhenPushed = YES;
            }
        }
            break;
        case 3://第三个分区
        {
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"dataForKeyAndUid"];
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"weixinLogin"];
            [self.navigationController popViewControllerAnimated:YES];
            self.tabBarController.tabBar.hidden = NO;
            self.tabBarController.selectedIndex = 2;
            UINavigationController *homeNavi = (UINavigationController *)self.tabBarController.viewControllers[2];
            homeNavi.hidesBottomBarWhenPushed = NO;
            
            HomeListViewController *homeLVC = (HomeListViewController *)homeNavi.viewControllers[0];
            [homeLVC createLoginView];
            
            //退出登录
            NSLog(@"退出登录");
        }
            break;
            
        default:
            break;
    }
}


#pragma mark - 清除缓存
- (void)cachesIsNull
{
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"暂无缓存" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil] ;
    [alert show];
    [self performSelector:@selector(missAlertView:) withObject:alert afterDelay:1.0];
}

- (void)sizeCecha
{
    NSString * filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches/default"];
    float result = [self folderSizeAtPath:filePath];
    _siziCache = result;
}

//清除缓存
- (void)clearCaches
{
    
    UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:[NSString stringWithFormat:@"缓存大小为%.2fM.确定要清理缓存吗?",_siziCache] delegate:self cancelButtonTitle:@"确认" otherButtonTitles:@"取消",nil];
    [alertView show ];
    
}

//代理方法
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    
    if(buttonIndex == 0)
    {
        NSFileManager * manger = [NSFileManager defaultManager];
        
        NSString *string = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches/default"];
        [manger removeItemAtPath:string error:nil];
        
        [self.mainTableView reloadData];
        
        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"清除缓存成功" delegate:nil cancelButtonTitle:nil otherButtonTitles: nil];
        [alert show];
        [self performSelector:@selector(missAlertView:) withObject:alert afterDelay:1.0];
        [self sizeCecha];
    }
}

- (void)missAlertView:(UIAlertView *)alert
{
    [alert dismissWithClickedButtonIndex:0 animated:YES];
}

- (long long)fileSizeAtPath:(NSString *)filePath
{
    NSFileManager * manager = [NSFileManager defaultManager];
    
    if([manager fileExistsAtPath:filePath])
    {
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0 ;
}

//计算沙盒的缓存
- (float)folderSizeAtPath:(NSString *)folderPath
{
    NSFileManager * manager = [NSFileManager defaultManager];
    //如果文件不存在，就返回0
    if (![manager fileExistsAtPath :folderPath])
    {
        return 0 ;
    }
    //NSEnumerator类似于NSArray，一般不单独使用。只是作为 NSArray，NSSet 和 NSDictionary 的辅助类
    //NSEnumerator 中的元素一旦遍历过之后就不能重新遍历，必须重新创建一个NSEnumerator。
    NSEnumerator * childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    
    NSString * fileName = [childFilesEnumerator nextObject];
    long long folderSize = 0 ;
    while((fileName = [childFilesEnumerator nextObject]) != nil)
    {
        NSString * fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        folderSize += [ self fileSizeAtPath:fileAbsolutePath];
    }
    return folderSize/ (1024.0  * 1024.0);
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
